﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Manage_ListUsers : System.Web.UI.Page
{
    protected class PowerInfo
    {
        public string ID
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public string Power
        {
            get;
            set;
        }

        public string District
        {
            get;
            set;
        }

        public string Belong
        {
            get;
            set;
        }
    }

    protected PagedDataSource pds = new PagedDataSource();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            XmlDataSource xds = new XmlDataSource();
            xds.DataFile = Toolkit.GetRealDataFilePath("Department.xml");
            xds.XPath = "/Root/District";
            Districts.DataSource = xds;
            Districts.DataTextField = "name";
            Districts.DataValueField = "name";
            Districts.DataBind();

            Districts.Items.Insert(0, new ListItem("请选择", ""));

            Departments.Items.Add(new ListItem("请选择", ""));


            BindData();
        }
    }

    private void BindData()
    {
        CmsDataContext db = new CmsDataContext();
        var q = from aM in db.Manager
                join aP in db.Power on aM.ID equals aP.ManagerID into tmp
                from aT in tmp.DefaultIfEmpty()
                where aT.Authority != (int)Powers.Teacher && aT.ManagerID != "back_admin"
                orderby aT.Authority
                select new { Manager = aM, Power = aT.Description };

        if (Districts.SelectedValue != "")
        {
            q = q.Where(aT => aT.Manager.District == Districts.SelectedValue);
        }
        if (Departments.SelectedValue != "")
        {
            q = q.Where(aT => aT.Manager.Belong == Departments.SelectedValue);
        }

        List<PowerInfo> pis = new List<PowerInfo>();
        foreach (var g in q.GroupBy(aT => aT.Manager))
        {
            Manager m = g.Key;
            string ps = "";
            foreach (var p in g)
            {
                ps += (ps == "" ? "" : ", ") + p.Power;
            }

            pis.Add(new PowerInfo() { ID = m.ID, Name = m.Name, Power = ps, District = m.District, Belong = m.Belong });
        }

        #region 检索条件
        string search = SearchConditionHidden.Value.Trim();
        if (search != "")
        {
            List<PowerInfo> bb = null;
            string[] ss = search.Split(' ');
            foreach (string s in ss)
            {
                Func<PowerInfo, bool> f = p => p.Name.Contains(s) || p.Power.Contains(s) || p.District.Contains(s) || p.Belong.Contains(s);
                bb = (bb == null) ? pis.Where(f).ToList() : bb.Union(pis.Where(f)).ToList();
            }

            pis = bb;
        } 
        #endregion

        pds = new PagedDataSource();
        pds.AllowPaging = true;
        pds.PageSize = Toolkit.PageSize;
        pds.DataSource = pis;

        #region 获取当前要显示的页
        int pageIndex = 0;
        pageIndex = Convert.ToInt32(CurrentPage.Value) - 1;
        if (pageIndex >= pds.PageCount)
        {
            pageIndex = pds.PageCount - 1;
        }
        if (pageIndex <= 0)
        {
            pageIndex = 0;
        }
        #endregion

        pds.CurrentPageIndex = pageIndex;

        UsersView.DataSource = pds;
        UsersView.DataBind();

        CurrentPage.Value = Convert.ToString(pageIndex + 1);
        SearchCondition.Text = SearchConditionHidden.Value.Trim();
    }

    protected void ChangePage(object sender, CommandEventArgs e)
    {
        string kind = Convert.ToString(e.CommandArgument);
        int p = Convert.ToInt32(CurrentPage.Value);

        if (kind == "F")
        {
            CurrentPage.Value = "1";
        }
        else if (kind == "P")
        {
            p--;
            CurrentPage.Value = Convert.ToString(p);
        }
        else if (kind == "N")
        {
            p++;
            CurrentPage.Value = Convert.ToString(p);
        }
        else if (kind == "L")
        {
            CurrentPage.Value = Convert.ToString(Int32.MaxValue);
        }
        else if (kind == "G")
        {
            TextBox gtp;
            foreach (Control c in UsersView.Controls)
            {
                gtp = c.FindControl("GotoPage") as TextBox;
                if (gtp != null)
                {
                    try
                    {
                        CurrentPage.Value = Convert.ToString(Convert.ToInt32(gtp.Text.Trim()));
                    }
                    catch
                    {
                        //CurrentPage.Value = "1";
                    }

                    break;
                }
            }
        }

        BindData();
    }

    protected void Search_Click(object sender, EventArgs e)
    {
        SearchConditionHidden.Value = SearchCondition.Text.Trim();
        BindData();
    }

    protected void DeleteUser_Click(object sender, EventArgs e)
    {
        string mids = Request.Params["chkID"];
        if (mids!=null && mids != "")
        {
            CmsDataContext db = new CmsDataContext();
            string[] ids = mids.Split(',');

            try
            {
                var q = from aM in db.Manager
                        where ids.Contains(aM.ID)
                        select aM;


                foreach (Manager manager in q)
                {
                    #region 删除用户权限
                    db.Power.DeleteAllOnSubmit(manager.Power);
                    #endregion

                    #region 删除用户日志
                    db.Logger.DeleteAllOnSubmit(manager.Logger);
                    #endregion

                    #region 将文章发表者置null
                    foreach (Article a in manager.CreatedArticles)
                    {
                        a.CreatorID = null;
                    }
                    #endregion

                    #region 将文章审核者置null
                    foreach (Article a in manager.VerifiedArticles)
                    {
                        a.VerifyID = null;
                    }
                    #endregion

                    #region 将教师审核员置null
                    foreach (Teacher teacher in manager.VerifiedTeachers)
                    {
                        teacher.VerfierID = null;
                    }
                    #endregion

                    #region 设置邀请中InviteID为null
                    foreach (Invite inv in manager.Invite)
                    {
                        inv.InvitorID = null;
                    }
                    #endregion

                    #region 设置Train的RegisterID为null
                    foreach (Train train in manager.Train)
                    {
                        train.RegisterID = null;
                    }
                    #endregion
                }

                #region 删除用户信息
                db.Manager.DeleteAllOnSubmit(q);
                #endregion

                //更新数据库
                db.SubmitChanges();

                MessageBox.Message = "所选择的用户已经成功删除。";
            }
            catch(Exception ee)
            {
                MessageBox.Message = "删除用户信息时发生错误。" + ee.Message;
            }

            BindData();
        }
    }
    protected void Districts_SelectedIndexChanged(object sender, EventArgs e)
    {
        Departments.Items.Clear();

        XmlDataSource xds = new XmlDataSource();
        xds.DataFile = Toolkit.GetRealDataFilePath("Department.xml");
        xds.XPath = string.Format("/Root/District[@name='{0}']//Depart", Districts.SelectedValue);

        Departments.DataSource = xds;
        Departments.DataTextField = "name";
        Departments.DataValueField = "name";
        Departments.DataBind();

        Departments.Items.Insert(0, new ListItem("请选择", ""));

        BindData();
    }
    protected void Departments_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindData();
    }
}